'use client';
import PageTitle from '@/components/admin/common/PageTitle';
import Loading from '@/components/common/Loading';
import message from '@/components/common/message';
import { SESSION_PERMISSIONS } from '@/config/settings';
import request from '@/utils/request';
import React, { useCallback, useEffect, useState } from 'react'
import buildPermissionTree from '@/utils/buildPermissionTree';

export default function Permissions() {
  const [loaded, setLoaded] = useState(false);
  const [permissionsTree, setPermissionsTree] = useState([]);

  const fetchPermissions = useCallback(() => {
    request('/api/admin/permissions', { method: 'GET' })
      .then(res => {
        if (res.code === 0) {
          setPermissionsTree(buildPermissionTree(res.data));
          sessionStorage.setItem(SESSION_PERMISSIONS, JSON.stringify(res.data));
        } else {
          message.error(res.codeMap[res.code]);
        }
      })
  }, []);

  useEffect(() => {
    if (sessionStorage.getItem(SESSION_PERMISSIONS)) {
      const permissions = JSON.parse(sessionStorage.getItem(SESSION_PERMISSIONS));
      setPermissionsTree(buildPermissionTree(permissions));
    } else {
      fetchPermissions();
    }
    setLoaded(true);
  }, [fetchPermissions]);

  const content = (
    <div>
      <PageTitle title="权限管理" />
      <div className='mx-auto bg-white rounded-sm my-2'>
        <div className='px-4 py-6' >
          <div>
            {
              permissionsTree.length > 0 && permissionsTree.map((item, index) => (
                <div key={index} className='flex flex-col px-2 pb-1'>
                  <div className='grid grid-cols-2 text-sm text-gray-700 border-gray-300 bg-[#FFFFFF] px-2 py-3 rounded-xs leading-5 border transition-all duration-100 cursor-pointer'>
                    <div>{item?.name}</div>
                    <div>{item?.path}</div>
                  </div>
                  {
                    item?.children?.length > 0 &&
                    <div className='ml-4'>
                      {
                        item?.children?.map(c => (
                          <div key={c.id} className='grid grid-cols-2 text-sm text-gray-700 border-gray-300 bg-[#FFFFFF] px-2 py-3 leading-5 rounded-xs border mt-1 transition-all duration-100 cursor-pointer'>
                            <div>{c.name}</div>
                            <div>{c.path}</div>
                          </div>
                        ))
                      }
                    </div>
                  }
                </div>
              ))
            }
          </div>
        </div>
      </div>
    </div >
  )

  return (
    <div>
      {loaded ? content : <Loading />}
    </div>
  )
}
